#include "stm32f10x.h"                  // Device header

extern uint16_t Num;

/*
1.RCC打开时钟[定时器的基准时钟和整个外设的工作时钟]
2.选择时基单元的时钟源
3.配置时基单元[包括预分频器,自动重装器,计数器的计数模式]
4.配置输出中断控制,允许更新中断输出到NVIC(开启中断)
5.配置NVIC,打开定时器中断的通道,分配中断优先级
6.启动定时器
7.运行控制
##注意使能计数器
*/
void Timer_Init(void)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
	
	// 选择时基源并配置时基单元
	TIM_InternalClockConfig(TIM2);
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruture;
	TIM_TimeBaseInitStruture.TIM_ClockDivision = TIM_CKD_DIV1; 		// 时钟信号分配数
	TIM_TimeBaseInitStruture.TIM_CounterMode = TIM_CounterMode_Up;  // 计数模式:上计数
	TIM_TimeBaseInitStruture.TIM_Period = 10000 - 1;     			// ARR的
	TIM_TimeBaseInitStruture.TIM_Prescaler = 60000 - 1;   			// PSC的
	TIM_TimeBaseInitStruture.TIM_RepetitionCounter = 0;  			// 重复计数器的
	TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruture);
	
	TIM_ClearFlag(TIM2, TIM_IT_Update);								// ?????????????
	TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);						// 使能中断, 选择"更新中断"
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);					// 优先级分组
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
	NVIC_Init(&NVIC_InitStructure);									// 别忘了Init初始化
	
	TIM_Cmd(TIM2, ENABLE);
}


void TIM2_IRQHandler(void)
{
	if (TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
	{
		Num++;
	}
	TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
